<script setup>
import { ref, reactive, inject } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "../stores/user";
const router = useRouter();
const route = useRoute();

const userStore = useUserStore();

const axios = inject("axios");

const isLogin = ref(true); // 状态：当前处于登录还是注册

const loginFormRef = ref();
const loginForm = reactive({
  account: "",
  password: "",
});
const loginRules = {
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};
const handleLogin = async () => {
  try {
    const res = await axios.post("/login", loginForm);
    // 登录响应
    const loginData = res.data.data;
    userStore.login(loginData);

    ElMessage.success("登录成功！");
    if (loginData.record.userType === 1) {
      router.push("/manageCenter/userManage"); // 管理员跳转到管理后台
    } else {
      router.push("/home"); // 普通用户跳转到首页
    }
    // if (res.data.code == 200) {
    //   ElMessage.success("登录成功！");
    //   // console.log(res.data);
    //   localStorage.setItem(
    //     "hudazx_vue_blogStorage",
    //     JSON.stringify(res.data.data)
    //   ); // 存储token

    //   const user = JSON.parse(localStorage.getItem("hudazx_vue_blogStorage"));

    //   if (user.record.userType == 1) {
    //     router.push("/manageCenter");
    //   } else {
    //     // 跳转到首页
    //     router.push("/welcome");
    //   }
    // } else {
    //   ElMessage.error("用户名或密码错误");
    // }
  } catch {
    ElMessage.error("用户名或密码错误");
  }
};

/* 3. 注册相关 */
const registerFormRef = ref();
const registerForm = reactive({
  username: "",
  account: "",
  password: "",
  confirmPassword: "",
});
// 自定义校验：确认密码必须和密码一致
const validateConfirm = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const registerRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 12, message: "账号长度在2到12个字符之间", trigger: "blur" },
  ],
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 18, message: "密码长度在6到18个字符之间", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validateConfirm, trigger: "blur" },
  ],
};
const handleRegister = async () => {
  try {
    const res = await axios.post("/register", registerForm);
    if (res.data.code == 200) {
      ElMessage.info("注册成功，请等待管理员审核");
      isLogin.value = true; // 切换到登录
    } else {
      ElMessage.error("服务异常");
    }
  } catch {
    ElMessage.error("服务异常");
  }
};
</script>

<template>
  <el-card class="login-card">
    <template #header>
      <div class="card-header">
        <!-- 切换按钮 -->
        <el-button-group>
          <el-button
            :type="isLogin ? 'primary' : ''"
            @click="isLogin = true"
            style="width: 80px"
          >
            登录
          </el-button>
          <el-button
            :type="!isLogin ? 'primary' : ''"
            @click="isLogin = false"
            style="width: 80px"
          >
            注册
          </el-button>
        </el-button-group>
      </div>
    </template>
    <!-- 登录表单 -->
    <el-form
      v-if="isLogin"
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-width="60px"
      class="form-box"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="loginForm.account" placeholder="请输入账号" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
    </el-form>

    <!-- 注册表单 -->
    <el-form
      v-else
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      label-width="80px"
      class="form-box"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="账号" prop="account">
        <el-input v-model="registerForm.account" placeholder="请输入账号" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="button-group">
        <el-button
          v-if="isLogin"
          type="primary"
          @click="handleLogin"
          class="button-style"
          >登录</el-button
        >
        <el-button
          v-else
          type="primary"
          @click="handleRegister"
          class="button-style"
        >
          注册</el-button
        >
      </div>
    </template>
  </el-card>
</template>

<style scoped>
.login-card {
  max-width: 500px;
  margin: 50px auto;
}

.card-header {
  display: flex;
  justify-content: center;
}

.button-group {
  display: flex;
  justify-content: center;
}

.button-style {
  width: 100px;
}

.form-box {
  margin-top: 24px;
}
</style>
